package com.singzi.leetcode.appo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class T17_11 {
}
class Solution17_11 {
    public int findClosest(String[] words, String word1, String word2) {
        List<Integer> word1List = new ArrayList<>();
        List<Integer> word2List = new ArrayList<>();
        int index = 0;
        for(String word:words){
            if(Objects.equals(word, word1)) {
                word1List.add(index);
                if(index > 0 && Objects.equals(words[index - 1], word2)) return 1;
            }
            else if(Objects.equals(word, word2)) {
                word2List.add(index);
                if(index > 0 && Objects.equals(words[index - 1], word1)) return 1;
            }
            index++;
        }
        Integer[] nums1 = word1List.toArray(new Integer[0]);
        Integer[] nums2 = word2List.toArray(new Integer[0]);
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int left = 0, right = 0,min = Integer.MAX_VALUE;
        while(left < nums1.length && right < nums2.length){
            if(Math.abs(nums1[left] - nums2[left]) == 1) return 1;
            if(nums1[left] > nums2[right]){
                min = Math.min(nums1[left] - nums2[right], min);
                right++;
            }else{
                min = Math.min(-nums1[left] + nums2[right], min);
                left++;
            }
        }
        return min;



    }
}